//
//  tagMusicPlayerView.m
//  tagPlayerModule
//
//  Created by liqian on 2018/10/22.
//  Copyright © 2018年 liqian. All rights reserved.
//
#define RGBCOLOR(r,g,b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

#define ImageNameUrl(name) [NSString stringWithFormat:@"tagPlayericon.bundle/%@",name]
#import "tagMusicPlayerView.h"

#import <AVFoundation/AVFoundation.h>
#ifdef DEBUG
#    define DLog(fmt,...) NSLog(fmt,##__VA_ARGS__)
#else
#    define DLog(fmt,...) /* */
#endif

@interface tagMusicPlayerView ()
@property (nonatomic, strong) UIImageView * iconImg;
@property (nonatomic, strong) UILabel     * timeLabel;
@property (nonatomic, strong) UIView      * pointView;

@property (nonatomic, strong) UIButton    * playBtn;
/**
 *  录音播放器player对象
 */
//@property (nonatomic,strong) AVAudioPlayer *player;

@property (nonatomic,strong) AVPlayer * player;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) id timeObserver;
//播放状态
@property (nonatomic, assign) VedioStatus playerStatus;
//总播放时长
@property (nonatomic, assign) CGFloat totalTime;

@end
@implementation tagMusicPlayerView
- (void)dealloc
{
    [self destroyPlayer];
    [self removeObserver:self forKeyPath:@"playerStatus"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:self.iconImg];
        [self addSubview:self.pointView];
        [self addSubview:self.timeLabel];
        [self addSubview:self.playBtn];
    }
    return self;
}
#pragma -<播放>
- (void)playButtonClick:(UIButton *)sender{
    
    if (self.player) {
        if (self.playerStatus == VedioStatusPause) {
            [self play];
            [self startAnimation];
        } else {
            [self pause];
            [self stopAnimation];
        }
    } else {
        [self initMusic];
        [self play];
        [self startAnimation];
    }
}
#pragma mark - <开始动画>
- (void)startAnimation{
    
    [self ActionWithImageName:@"icon" imageCount:3 praiseImage:self.iconImg duration:1];
}
#pragma mark - <停止动画>
- (void)stopAnimation{
    [self.iconImg stopAnimating];
}

#pragma mark 初始化播放文件，只允许在播放按钮事件使用
- (void)initMusic {
    self.player = [[AVPlayer alloc]init];
   
    [self initPlayerItem];
    [self addPlayerListener];
}

//修改playerItem
- (void)initPlayerItem {
    if (self.pathUrl && ![self.pathUrl isEqualToString:@""]) {
        AVAsset * aset = [AVAsset assetWithURL:[NSURL URLWithString:self.pathUrl]];
        self.playerItem = [AVPlayerItem playerItemWithAsset:aset];
        [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
    }
}


//添加监听文件,所有的监听
- (void)addPlayerListener {
    
    //自定义播放状态监听
    [self addObserver:self forKeyPath:@"playerStatus" options:NSKeyValueObservingOptionNew context:nil];
    if (self.player) {
        //播放速度监听
        [self.player addObserver:self forKeyPath:@"rate" options:NSKeyValueObservingOptionNew context:nil];
    }
    
    if (self.playerItem) {
        //播放状态监听
        [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        //缓冲进度监听
        [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
        
        //播放中监听，更新播放进度
        __weak typeof(self) weakSelf = self;
        self.timeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 30) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
            float currentPlayTime = (double)weakSelf.playerItem.currentTime.value/weakSelf.playerItem.currentTime.timescale;
            if (weakSelf.playerItem.currentTime.value<0) {
                currentPlayTime = 0.1; //防止出现时间计算越界问题
            }
            
        }];
        
    }
    
    //给AVPlayerItem添加播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    //监听应用后台切换
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appEnteredBackground)
                                                 name:UIApplicationDidEnterBackgroundNotification
                                               object:nil];
    //播放中被打断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
    //拔掉耳机监听？？
}

#pragma mark 播放，暂停
- (void)play{
    if (self.player && self.playerStatus == VedioStatusPause) {
        NSLog(@"通过播放停止");
        self.playerStatus = VedioStatusBuffering;
        [self.player play];
    }
}

- (void)pause{
    if (self.player && self.playerStatus != VedioStatusPause) {
        NSLog(@"通过暂停停止");
        [self stopAnimation];
        self.playerStatus = VedioStatusPause;
        [self.player pause];
    }
}


#pragma mark 监听播放完成事件
-(void)playerFinished:(NSNotification *)notification{
    NSLog(@"播放完成");
    [self.playerItem seekToTime:kCMTimeZero];
    [self pause];
}

#pragma mark 播放被打断
- (void)handleInterruption:(NSNotification *)notification {
    [self pause];
}

#pragma mark 监听捕获
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item = (AVPlayerItem *)object;
        if ([self.playerItem status] == AVPlayerStatusReadyToPlay) {
            //获取音频总长度
            CMTime duration = item.duration;
            [self setMaxDuratuin:CMTimeGetSeconds(duration)];
            NSLog(@"AVPlayerStatusReadyToPlay -- 音频时长%f",CMTimeGetSeconds(duration));
            
        }else if([self.playerItem status] == AVPlayerStatusFailed) {
            
            [self playerFailed];
            NSLog(@"AVPlayerStatusFailed -- 播放异常");
            
        }else if([self.playerItem status] == AVPlayerStatusUnknown) {
            
            [self pause];
            NSLog(@"AVPlayerStatusUnknown -- 未知原因停止");
        }
    } else if([keyPath isEqualToString:@"loadedTimeRanges"]) {
        AVPlayerItem *item = (AVPlayerItem *)object;
        NSArray * array = item.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue]; //本次缓冲的时间范围
        NSTimeInterval totalBuffer = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration); //缓冲总长度
//        self.timeSlider.trackValue = totalBuffer;
        //当缓存到位后开启播放，取消loading
        if ( self.playerStatus != VedioStatusPause && totalBuffer > 1 ) {
            [self.player play];
        }
        NSLog(@"---共缓冲---%.2f",totalBuffer);
    } else if ([keyPath isEqualToString:@"rate"]){
        AVPlayer *item = (AVPlayer *)object;
        if (item.rate == 0) {
            if (self.playerStatus != VedioStatusPause) {
                self.playerStatus = VedioStatusBuffering;
            }
        } else {
            self.playerStatus = VedioStatusPlaying;
            
        }
        NSLog(@"---播放速度---%f",item.rate);
    } else if([keyPath isEqualToString:@"playerStatus"]){
        switch (self.playerStatus) {
            case VedioStatusBuffering:
                
                break;
            case VedioStatusPause:
                
                break;
            case VedioStatusPlaying:
                
                break;
                
            default:
                break;
        }
    }
}
//计算时间
- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (second/3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    } else {
        [formatter setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [formatter stringFromDate:d];
    return showtimeNew;
}

#pragma mark 设置时间轴最大时间
- (void)setMaxDuratuin:(float)duration{
    _totalTime = duration;
    self.timeLabel.text = [self convertTime:duration];
}
//销毁player,无奈之举 因为avplayeritem的制空后依然缓存的问题。
- (void)destroyPlayer {
    
    [self.playerItem removeObserver:self forKeyPath:@"status"];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [self.player removeObserver:self forKeyPath:@"rate"];
    [self.player removeTimeObserver:self.timeObserver];
    
    self.playerItem = nil;
    self.player = nil;
    
    self.playerStatus = VedioStatusPause;
//    self.timeNowLabel.text = @"00:00";
}
#pragma mark 播放失败
-(void)playerFailed{
    NSLog(@"播放失败");
    [self destroyPlayer];
}
#pragma mark - <UI>
- (UIImageView *)iconImg{
    
    if (!_iconImg) {
        
        _iconImg = [[UIImageView alloc] init];
        _iconImg.image = [UIImage imageNamed:ImageNameUrl(@"music")];
//        _iconImg.backgroundColor = [UIColor redColor];
    }
    return _iconImg;
    
}

- (UIView *)pointView{
    if (!_pointView) {
        
        _pointView = [[UIView alloc] init];
        _pointView.backgroundColor = RGBCOLOR(64,229,191);
    }
    return _pointView;
}

- (UILabel *)timeLabel{
    if (!_timeLabel) {
        
        _timeLabel = [[UILabel alloc] init];
//        _timeLabel.text = [NSString stringWithFormat:@"52”"];
        _timeLabel.font = [UIFont systemFontOfSize:15];
        _timeLabel.textAlignment = NSTextAlignmentRight;
    }
    return _timeLabel;
}


- (UIButton *)playBtn{
    
    if (!_playBtn) {
        _playBtn = [[UIButton alloc] init];
        [_playBtn addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playBtn;
}


/**
 动画播放

 @param imageName 图片名称
 @param imageCount 图片数量
 @param praiseImage
 @param duration
 */
- (void)ActionWithImageName:(NSString *)icon imageCount:(NSInteger)imageCount praiseImage:(UIImageView *)praiseImage duration:(NSTimeInterval)duration{
    //存储一组图片的数组
    NSMutableArray *imageArry = [NSMutableArray arrayWithCapacity:1];
    for (int i = 1; i <= imageCount; i++) {
        //图片名
        NSString *name = [NSString stringWithFormat:@"%@%d.png",icon, i];
        //图片对象
        UIImage *image = [UIImage imageNamed:ImageNameUrl(name)];
        //image 添加到数组 imageArry
        [imageArry addObject:image];
    }
    //设置动态播放的图片
    praiseImage.animationImages = imageArry;
    //设置图片播放的时间
    praiseImage.animationDuration = duration;
    //设置图片播放的次数
    praiseImage.animationRepeatCount = -1;
    //播放图片
    [praiseImage startAnimating];
    
}

/**
 接收音频地址信息

 @param pathUrl 链接
 */

- (void)setPathUrl:(NSString *)pathUrl{
    _pathUrl = pathUrl;
    
}



/**
 刷新UI
 */
- (void)layoutSubviews{
    [super layoutSubviews];
    NSLog(@"%@",self);
    
    self.iconImg.frame = CGRectMake(15, 10, self.frame.size.height-20, self.frame.size.height-20);
    self.pointView.frame = CGRectMake(self.frame.size.width-23, (self.frame.size.height-4)/2, 8, 8);
    self.pointView.layer.cornerRadius = self.pointView.frame.size.width/2;
    self.pointView.clipsToBounds  = YES;
    self.timeLabel.frame = CGRectMake(self.iconImg.frame.size.width+self.iconImg.frame.origin.x+10, (self.frame.size.height-15)/2, self.frame.size.width-(self.iconImg.frame.size.width+self.iconImg.frame.origin.x+10+27), 15);
    
    self.playBtn.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    
}
@end
